import axios from 'axios'
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse
} from 'axios'
import useUserStore from '@/store/user'
import { useNavigate } from 'react-router-dom'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: 'http://localhost:23892',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么
    const { token } = useUserStore.getState()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    return res
  },
  (error) => {
    // 处理 HTTP 错误
    let message = 'Network error'
    const navigate = useNavigate()
    if (error.response) {
      switch (error.response.status) {
        case 401:
          message = '您的登录已过期，请重新登录'
          navigate('/login')
          break
        case 403:
          message = 'Forbidden'
          break
        case 404:
          message = 'Not found'
          break
        case 500:
          message = 'Server error'
          break
        default:
          message = `Error: ${error.response.status}`
      }
    }
    console.error('Response error:', message)
    return Promise.reject(error)
  }
)

// 封装 GET 请求
export function get<T>(
  url: string,
  params?: unknown,
  config?: InternalAxiosRequestConfig
): Promise<T> {
  return service.get(url, { params, ...config })
}

// 封装 POST 请求
export function post<T>(
  url: string,
  data?: unknown,
  config?: InternalAxiosRequestConfig
): Promise<T> {
  return service.post(url, data, config)
}

// 封装 PUT 请求
export function put<T>(
  url: string,
  data?: unknown,
  config?: InternalAxiosRequestConfig
): Promise<T> {
  return service.put(url, data, config)
}

// 封装 DELETE 请求
export function del<T>(
  url: string,
  params?: unknown,
  config?: InternalAxiosRequestConfig
): Promise<T> {
  return service.delete(url, { params, ...config })
}

export default service
